<script lang="ts" setup>
import { onMounted, reactive, ref, watch } from 'vue';
import API from '@/services';
import AQueryHeader, { useQueryHeader } from '@dangojs/a-query-header';
import AQueryTable from '@dangojs/a-query-table';
import TimePicker from '@/arco-components/time-picker.vue';
import * as RouteNames from '@/router/consts';
import { useRouter } from 'vue-router';
import { useStore } from '@/store';
import UserSelect from '@/arco-components/select/user-select/index.vue';
import { Message, Modal } from '@arco-design/web-vue';

interface FormDataI {
  tableName: string | undefined;
  tableType: string | undefined;
  createBy: string | undefined;
  startTime: string | undefined;
  endTime: string | undefined;
}

const formData = reactive<FormDataI>({
  tableName: undefined,
  tableType: undefined,
  createBy: undefined,
  startTime: undefined,
  endTime: undefined
});
const store = useStore();
const props = defineProps({
  addDataTable: {
    type: Boolean,
    default: false
  }
});
const querytableRef = ref<any>(null);
const columns: any[] = [
  {
    title: 'ID',
    dataIndex: 'id',
    width: 80
  },
  {
    title: '表名称',
    slotRenderName: 'tableName',
    width: 160
  },
  {
    title: '表用途',
    dataIndex: 'tableTypeName',
    width: 160
  },
  {
    title: '占用空间',
    dataIndex: 'tableUsedSize',
    width: 160
  },
  {
    title: '创建人',
    dataIndex: 'createByName',
    width: 160
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
    width: 180
  },
  {
    title: '操作',
    width: 160,
    fixed: 'right',
    slotRenderName: 'operate'
  }
];
const requestData = async (query: any) => {
  try {
    const res = await API.dataTable.postDataTablePageQuery(query);
    if (res.data) {
      return {
        success: true,
        data: res.data.list,
        total: res.data.total
      };
    }
    return {
      success: true,
      data: [],
      total: 0
    };
  } catch (e) {}
};

const router = useRouter();
// 去往详情页
const goDetail = (props: any) => {
  let { id, createByName, createTime, tableName, tableDesc, synColumnStatus } =
    props;
  store.commit('datamanage/setTableDetail', {
    id,
    createByName,
    createTime,
    tableName,
    tableDesc,
    synColumnStatus
  });
  router.push({
    name: RouteNames.ROUTER_DATAMANAGEDETAIL,
    query: {
      id
    }
  });
};
// const { onSubmit, onReset, params } = useQueryHeader(formData);
const { onAutoSubmit, onReset, params } = useQueryHeader(formData, true);
const typeOptions = ref<any[]>([]);
const getTypeData = async () => {
  try {
    const res = await API.enumBao.getGetTableType();
    typeOptions.value = res?.data || [];
  } catch (e) {
    typeOptions.value = [];
  }
};
watch(
  () => props.addDataTable,
  (val) => {
    if (val) {
      onReset();
    }
  }
);
onMounted(() => {
  getTypeData();
});
const fetchDelete = async (id: any) => {
  try {
    let res = await API.dataTable.deleteDataTableDeleteById({ id });
    // todo: API接口出错不会出现异常
    return res;
  } catch (error) {
    throw error;
  }
};
const onDelete = (record: any) => {
  Modal.confirm({
    modalClass: 'model-message-confirm',
    title: '是否确定删除该数据表？',
    content: '删除后不可恢复',
    simple: false,
    closable: true,
    okText: '确认删除',
    okButtonProps: {
      style: {
        backgroundColor: '#FF1A3B'
      }
    },
    onBeforeOk: (done) => {
      fetchDelete(record.id)
        .then((res: any) => {
          if (res.code === 200) {
            Message.success('删除成功');
            // todo: 当前页最后一条怎么办
            querytableRef.value.reload();
          } else {
            Message.error(res.msg);
          }
        })
        .finally(() => {
          done(true);
        });
    }
  });
};
const uploadTable = () => {
  onReset();
};
defineExpose({ uploadTable });
</script>

<template>
  <div>
    <div class="p-18">
      <AQueryHeader
        @reset="onReset"
        hideSubmitBtn
        @autoSubmit="onAutoSubmit"
        rows-num="2"
      >
        <AFormItem show-colon label="表名称">
          <AInput v-model="formData.tableName" placeholder="请输入" />
        </AFormItem>
        <AFormItem show-colon label="类型">
          <ASelect
            v-model="formData.tableType"
            :options="typeOptions"
            placeholder="请输入"
          />
        </AFormItem>
        <AFormItem show-colon label="创建人">
          <UserSelect v-model="formData.createBy" placeholder="请输入" />
        </AFormItem>
        <AFormItem show-colon label="创建时间">
          <TimePicker
            v-model:startTime="formData.startTime"
            v-model:endTime="formData.endTime"
          />
        </AFormItem>
      </AQueryHeader>
    </div>

    <a-divider />
    <AQueryTable
      ref="querytableRef"
      :columns="columns"
      :request="requestData"
      :params="params"
      class="p-18"
    >
      <template #tableName="{ record }">
        <a-button type="text" @click="() => goDetail(record)">{{
          record.tableName
        }}</a-button>
      </template>
      <template #operate="{ record }">
        <a-button type="text" @click="() => onDelete(record)">删除</a-button>
      </template>
    </AQueryTable>
  </div>
</template>
<style lang="scss" scoped>
@import './index.scss';
</style>
